package com.repair.sms.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.repair.sms.service.SmsService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.aliyun.teautil.Common.toJSONString;

/**
 * @author chunyu
 * @since 2024/9/18,19:18
 */
@Slf4j
@Getter
@Setter
@Service
public class SmsServiceImpl implements SmsService {

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String signName;

    private String templateCode;

    public Client createClient() throws Exception {
        Config config = new Config()
                // 配置 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 配置 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);

        // 配置 Endpoint
        config.endpoint = endpoint;

        return new Client(config);
    }


    @Override
    public boolean sendMessage(String telephone, String captcha) {
        SendSmsResponse sendSmsResponse = null;
        try {
            // 初始化请求客户端
            Client client = createClient();

            // 组装param
            String param = "{\"code\": \"" + captcha + "\"}";

            // 构造请求对象，请填入请求参数值
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(telephone)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(param);

            // 获取响应对象
            sendSmsResponse = client.sendSms(sendSmsRequest);
            System.out.println(sendSmsResponse);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信三方调用异常 sendSmsResponse:{}", toJSONString(sendSmsResponse));
            return false;
        }
        return true;
    }
}
